package com.codeoss.framework.view.util;

import java.util.HashMap;
import java.util.Map;

import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.data.metadata.Column;
import com.codeoss.framework.data.metadata.Query;
import com.codeoss.framework.data.metadata.Restrictions;
import com.codeoss.framework.data.metadata.Table;
import com.codeoss.framework.data.metadata.TableData;
import com.codeoss.framework.view.datasource.IDataSource;

public class TableCRUDRuleContext {
	private YunContext yunContext;
	private Table table;
	private Map<String, Object> dataMap;
	private Map<String, Object> dbDataMap;
	private Map<String, Object> parentDBDataMap;
	private IDataSource dataSource;
	private Table parentTable;
	private IDataSource parentDataSource;
	
	public Map<String,Object> getDBMap(){
		if(dbDataMap==null) {
			Column column=table.getPrimaryKeyColumn();
			Query query=new Query();
			query.add(Restrictions.eq(column.getColumnName(), dataMap.get(column.getColumnName())));
			TableData tableData=dataSource.select(yunContext, table, query);
			if(tableData.getData()!=null&&tableData.getData().size()>0) {
				dbDataMap=tableData.getData().get(0);
			}
		}
		return dbDataMap;
	}
	
	public Map<String,Object> getParentDBMap(){
		if(parentDBDataMap==null) {
			if(parentTable==null) {
				parentDBDataMap=new HashMap<String, Object>();
			}else {
				Map<String,Object> dataMap=getDBMap();
				Query query=new Query();
				query.add(Restrictions.eq(parentTable.getPrimaryKeyColumn().getColumnName(), dataMap.get(table.getParentColumn().getColumnName())));
				TableData tableData=dataSource.select(yunContext, parentTable, query);
				if(tableData.getData()!=null&&tableData.getData().size()>0) {
					parentDBDataMap=tableData.getData().get(0);
				}
			}
		}
		return parentDBDataMap;
	}
	
	public YunContext getYunContext() {
		return yunContext;
	}
	public void setYunContext(YunContext yunContext) {
		this.yunContext = yunContext;
	}
	public Table getTable() {
		return table;
	}
	public void setTable(Table table) {
		this.table = table;
	}
	public Map<String, Object> getDataMap() {
		return dataMap;
	}
	public void setDataMap(Map<String, Object> dataMap) {
		this.dataMap = dataMap;
	}

	public IDataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(IDataSource dataSource) {
		this.dataSource = dataSource;
	}

	public Table getParentTable() {
		return parentTable;
	}

	public void setParentTable(Table parentTable) {
		this.parentTable = parentTable;
	}

	public IDataSource getParentDataSource() {
		return parentDataSource;
	}

	public void setParentDataSource(IDataSource parentDataSource) {
		this.parentDataSource = parentDataSource;
	}
}
